package com.compus_help.interceptor;


import com.compus_help.common.Constants;
import com.compus_help.common.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取Token
        String token = request.getHeader(Constants.TOKEN_HEADER);
        String uri = request.getRequestURI();
        System.out.println("请求URI: " + uri); // 添加调试日志

        // 检查是否应该排除
        if (uri.equals("/admin/login") || uri.equals("/admin/test")) {
            return true; // 允许通过
        }

        // 如果Token为空，返回未授权错误
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\": 401, \"message\": \"未提供认证令牌\"}");
            return false;
        }

        // 移除Bearer前缀（如果存在）
        if (token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }

        // 验证Token是否有效
        if (!jwtUtil.validateToken(token) || jwtUtil.isTokenExpired(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\": 401, \"message\": \"认证令牌无效或已过期\"}");
            return false;
        }

        // 将用户ID和角色信息存入请求属性，方便后续使用
        Long userId = jwtUtil.getUserIdFromToken(token);
        String role = jwtUtil.getRoleFromToken(token);
        request.setAttribute(Constants.USER_ID_ATTRIBUTE, userId);
        request.setAttribute(Constants.USER_ROLE_ATTRIBUTE, role);


        return true;
    }
}